<!--
 * @Author: Mcc
 * @Date: 2024-07-30 16:22:29
 * @LastEditors: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @LastEditTime: 2024-10-16 11:38:06
 * @FilePath: \ft-apply-admin\src\views\TrainList\trainList.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by Mcc, All Rights Reserved. 
-->
<template>
  <div id="trainList">
    <div class="tops" v-if="false">
      <div class="titles">
        <h2 class="title">培训列表</h2>
        <div class="times">
          <Button type="primary" :icon="h(PlusSquareOutlined)" @click='addTrain(0, "")'>新增培训</Button>
        </div>
      </div>
      <!-- <div class="contents">
        <div class="all_Btn" @click="toggleSelectAll" :class='isAllSelected ? "allSelect" : ""'>
          全部（{{ totalCount }}）
        </div>
        <div>
          <ul class="top_ul">
            <li v-for="(stage, index) in stages" :key="index" @click="selectStage(index)" :class="{
              'selected': selectedIndex === index,
              'before-green': index <= selectedIndex
            }">
              &nbsp;&nbsp;&nbsp;{{ stage.name }}（{{ stage.count }}）
            </li>
          </ul>
        </div>
      </div> -->
    </div>
    <div class="bottom_table">
      <div class="flex justify-between">
        <h2 class="title">培训列表</h2>
        <Button v-auth="'addTraining'" type="primary" :icon="h(PlusSquareOutlined)"
          @click='addTrain(0, "")'>新增培训</Button>
      </div>
      <div class="result-wrap" v-if="resultList.length > 0">
        <div class="inner">
          <span v-for="item in resultList" class="result-item">
            {{ item.value }}
            <CloseOutlined @click="remove(item)" />
          </span>
          <span @click="removeAll" class="result-clear">清空条件</span>
        </div>
      </div>
      <BasicTable :scroll="{ x: false, y: 695 }" :multiple-sort="true" rowKey="trainingNumberId"
        @register="registerTable"  size="small">
        <template #headerCell="{ column }">
          <template v-if="column.tooltip">
            {{ column.title }}
            <a-tooltip placement="top" class="ml-3px" :title="column.tooltip">
              <img src="@/assets/icon/tooltip.svg" />
            </a-tooltip>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'edit'">
            <span class="flex items-center gap-3 justify-center ">
              <i :disabled="record.appointmentNumber != 0" v-auth="'editTraining'" @click='addTrain(1, record)'
                class="iconfont icon-bi color-#209ee4 cursor-pointer "></i>
              <a-popconfirm title="是否确认删除?" placement="leftTop" ok-text="确认" cancel-text="取消" @confirm="delTrain(record)">
                <i v-auth="'editTraining'" :class="[record.appointmentNumber != 0 ? 'cannot-click' : '']"
                  class="iconfont icon-shanchu color-#FF4242 cursor-pointer "></i>
              </a-popconfirm>
            </span>
          </template>
          <template v-if="column.key === 'online'">
            <span class="flex items-center gap-1 justify-center">
              <a-switch :checked="record.isOnline === 1"  @change="handleOnlineChange(record)" />
            </span>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :class="getTagClassStatus(record.status)" class="custom-tag">{{ record.status }}</a-tag>
          </template>
          <template v-if="column.key === 'trainingNumberName'">
            <Button type="link" @click="goDetail(record)" class="btn-hover">{{ record.trainingNumberName }}</Button>
          </template>
        </template>
        <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, visible, clearFilters, column }">
          <Dropdown :column="column" :state="state" @handleReset="handleReset(column)"
            @handleSearch="handleSearch(selectedKeys, confirm, column)"
            @handleInputChange="handleInputChange($event, column)" @onCheckAllChange="onCheckAllChange(column)"
            @onCheckChange="onCheckChange(column)" />
        </template>
      </BasicTable>
      <div style="display: flex;align-items: baseline;" class="table_btnC" v-if="tableData && tableData.length > 0">
        <a-checkbox v-model:checked="allchecked" @click="selectAllRows">全选</a-checkbox>
        <Button v-auth="'batchEditTraining'" :style="{ color: getSelectRows().length > 0 ? '#209eff' : '' }" class="btn"
          size='default' @click='batchTrain'>批量编辑</Button>
        <!--暂时不做 <Button class="btn" type="primary" size='default' style="margin-left: 10px;">数据导出</Button> -->
      </div>
    </div>
    <Modal @register="registerModal" @success="handleSuccess" :minHeight="100" />
    <BatchModal @register="batchModal" @success="batchModalHandleSuccess" :minHeight="100" />
  </div>
</template>
<script lang="ts">//动态设置组件名称
import { defineComponent } from 'vue';
let name = ''
const getLastPathSegment = () => {
  const url = window.location.hash; // 获取 URL 中的 hash 部分（包括 #）
  const pathSegments = url.split('/'); // 根据 '/' 分割
  return pathSegments[pathSegments.length - 1] || ''; // 返回最后一段路径
};
name = getLastPathSegment()
export default defineComponent({
  name: name,
});
</script>

<script lang="ts" setup>
import {
  PlusSquareOutlined,
  SearchOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  EditOutlined
} from '@ant-design/icons-vue';
import { h, ref, computed, onMounted, onBeforeMount, onActivated } from 'vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { columns, getStatusFun, selectOptions, navStatusType } from './components/data.ts';
import { Checkbox, CheckboxGroup, message } from 'ant-design-vue';
import { Button } from '@/components/Button'
import { useModal } from '@/components/Modal';
import Modal from './components/Modal.vue';
import BatchModal from './components/batchModal.vue';
import { useUserStore } from '@/store/modules/user'
import Dropdown from '@/views/DataCenter/HRData/components/Dropdown.vue'
import { useTableInit } from '@/views/DataCenter/HRData/components/useTableInit.js'
import { selectTrainingNumberPage, selectTrainingNumberAllList, deleteTrainingNumber, updateOnlineStatus } from '@/api/applay/trainlist/self'
import { useRoute, useRouter } from "vue-router";
import { selectTrainingNumberList, selectCommonConfigDetail } from "@/api/application-details/index.ts";
import { tabulationStatusList } from '@/api/applay/applicationList/self.ts'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
import type { Dayjs } from 'dayjs';
type RangeValue = [Dayjs, Dayjs];
const rangeValue = ref<RangeValue>();
const getData = async () => {
  //const res = await selectTrainingNumberPage("");
  //console.log(res)
}
const totalCount = 1300;
const stages = [
  { name: '未开始', count: 1600000 },
  { name: '培训中', count: 160000 },
  { name: '考核中', count: 16000 },
  { name: '已结束', count: 1600 }
];
const allchecked = ref(false);
const [registerModal, { openModal: openModal }] = useModal();
const [batchModal, { openModal: batchOpenModal }] = useModal();
const addTrain = (types, record) => {
  openModal(true, {
    nums: types,
    value: record
  }, true, {
    centered: true
  });
}
//table编辑
const getButtonPropsEdit = (edit) => {
  switch (edit) {
    case 0:
      return { type: 'primary', danger: false, disabled: false };
    case 1:
      return { type: 'primary', danger: true, disabled: false };
    case 2:
      return { type: 'primary', danger: false, disabled: true };
    default:
      return { type: 'primary', danger: false, disabled: false };
  }
};
//table
const getButtonPropsStatus = (status) => {
  switch (status) {
    case "未开始":
      return { type: 'link', danger: false, disabled: false };
    case "进行中":
      return { type: 'link', danger: true, disabled: false };
    case "已结束":
      return { type: 'link', danger: false, disabled: true };
    default:
      return { type: 'link', danger: false, disabled: false };
  }
};

const getTagClassStatus = (status) => {
  switch (status) {
    case "未开始":
      return 'tag-not-start';
    case "培训中":
      return 'tag-progress';
    case "已结束":
      return 'tag-over';
    default:
      return 'tag-normal';
  }
};



//新增和编辑成功后回调
function handleSuccess(data) {
  message.success(data.trainingNumberId ? '编辑成功' : '新增成功')
  reload()
  //回来后关闭弹框
  openModal(false)
}
//批量成功后回调
function batchModalHandleSuccess() {
  message.success('批量修改成功')
  reload()
  allchecked.value = false
  //回来后关闭弹框
  batchOpenModal(false);
}

//表格操作
const resultList = ref<any>([]);
const tableData = <any>ref([])
const state = ref<any>({}) // 状态
const getStatus = ref();
onBeforeMount(async () => {
  //通过route来判定是在哪个页面调用不同的接口
  console.log(route.name)
  if (route.name == 'pxall') {
    getStatus.value = "";
  } else if (route.name == 'pxwks') {
    getStatus.value = 0;
  } else if (route.name == 'pxing') {
    getStatus.value = 1;
  } else if (route.name == 'pxkhz') {
    getStatus.value = 2;
  } else if (route.name == 'pxyjs') {
    getStatus.value = 3;
  }
  getStatusFun(getStatus.value)
  await getOptions()
  // 初始化state数据
  initState(options)
})


const {
  initState,
  handleSearch,
  onCheckAllChange,
  onCheckChange,
  handleInputChange,
  handleReset,
  removeAll,
  remove,
} = useTableInit({ state, tableData, columns, resultList, searchFun })

const [registerTable, { reload, setPagination, getForm, getPaginationRef, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys }] = useTable({
  title: '',
  //dataSource: tableData,
  api: selectTrainingNumberPage,
  columns,
  formConfig: {
    labelWidth: 120,
    //schemas: searchFormSchema,
    autoSubmitOnEnter: true,
    showAdvancedButton: true,
    autoAdvancedLine: 4,
    showSubmitButton: false,
  },
  pagination: {
    pageSize: 50, // 设置每页显示 50 条数据
    // 可以添加更多 pagination 的配置
  },
  rowSelection: {
    type: 'checkbox',
    getCheckboxProps(record) {
      // Demo: 第一行（id为0）的选择框禁用
      if (record.status === 2) {
        return { disabled: true };
      } else {
        return { disabled: false };
      }
    },
  },
  useSearchForm: false,
  showTableSetting: false,
  showIndexColumn: false,
  bordered: true,
  canResize: true,
  clickToRowSelect: false,
  beforeFetch(info) {
    // console.log(resultList.value,'resultList.value')
    // 处理请求前的参数
    try {
      resultList.value.forEach(v => {
        if (v.formType == 'time') {
          if (v.params?.length) {
            v.params.forEach((item, index) => {
              info[item] = v.inputValue[index]
            })
          } else {
            info[v.key] = v.inputValue
          }
        } else if (v.formType == 'cascader') {
          if (v.checkedList?.length && v.checkedList[0]?.length == 3) {
            let list = [] as any
            v.checkedList.forEach(item => {
              list.push(item[2])
              info[v.params || v.key] = list
            })
          } else {
            info[v.params || v.key] = v.checkedList
          }
        } else {
          info[v.params || v.key] = v.checkedList
        }
      })
      if (!info.statusList) {
        info.status = getStatus.value
      }
    } catch (error) {
      console.log(error)
    }
  },
  sortFn(sortInfo) {
    if (sortInfo.order) {
      return { sortingFields: [{ field: sortInfo.field, order: sortInfo.order === 'descend' ? 'desc' : 'asc' }] }
    } else {
      return {}
    }
  },
  afterFetch(list) {
    tableData.value = list
  }
})
onActivated(async () => {
  console.log(route.name)
  if (route.name == 'pxall') {
    getStatus.value = "";
  } else if (route.name == 'pxwks') {
    getStatus.value = 0;
  } else if (route.name == 'pxing') {
    getStatus.value = 1;
  } else if (route.name == 'pxkhz') {
    getStatus.value = 2;
  } else if (route.name == 'pxyjs') {
    getStatus.value = 3;
  }
  getStatusFun(getStatus.value)
  await getOptions()
  // 初始化state数据
  initState(options)
  reload();
})

// 搜索
function searchFun() {
  reload()
}

// 获取远程下拉数据
const options = ref({
  trainingNumberName: [],
  status: []
})
async function getOptions() {
  // 培训期数
  const { data: trainingNumberName } = await selectTrainingNumberAllList()
  options.value.trainingNumberName = trainingNumberName.map(v => {
    return {
      label: v.trainingNumberName,
      value: v.trainingNumberId
    }
  })
  // 状态合集
  const { data: status } = await selectCommonConfigDetail({ type: 'TRAINING' })
  options.value.status = status
}

// 选中所有行
function selectAllRows() {
  if (!allchecked.value) {
    const allKeys = tableData.value.map((row: any) => row.trainingNumberId)
    setSelectedRowKeys(allKeys)
  } else {
    clearSelectedRowKeys()
  }
}

//批量操作
const batchTrain = (types, record) => {
  let selects = getSelectRows();
  if (selects.length > 0) {
    batchOpenModal(true, {
      value: selects
    }, true, {
      centered: true
    });
  } else {
    message.error('你还没选择数据');
  }
}

const delTrain = async (item) => {
  const data = await deleteTrainingNumber({
    trainingNumberId: item.trainingNumberId
  })
  console.log(data, '===>data')
  if (data.code &&data.code != '10000') {
    message.error(data.msg)
    return
  }
  message.success('删除成功')
  reload()

}

const handleOnlineChange = async (item) => {
  console.log(item, '===>item')
  const { trainingNumberId, isOnline } = item
  const data = await updateOnlineStatus({
    trainingNumberId,
    trainingOnlineStatus: isOnline == 0 ? 1 : 0
  })
  console.log(data)
  if (data.code && data.code != '10000') {
    message.error(data.msg);
    return
  }
  message.success('更新成功');
  reload();
}

// 培训详情
function goDetail(data) {
  router.push(
    {
      path: "/trainDetails/trainDetails",
      query: {
        trainingNumberId: data.trainingNumberId
      }
    }
  )
}
</script>
<style lang="less" scoped>
:deep(::-webkit-scrollbar) {
  width: 8px;
  /* 滚动条宽度 */
  height: 8px !important;
  /* 滚动条高度 */
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background-color: #dddddd !important;
  /* 鼠标悬停时滚动条拇指颜色 */
}

:deep(.boxGroup) {
  display: flex;
  flex-direction: column;
}

#trainList {
  .tops {
    background: #FFFFFF;
    padding: 20px 30px;
    border-radius: 10px;

    .titles {
      display: flex;
      justify-content: space-between;
    }

    .contents {
      display: flex;
      align-items: baseline;

      .allSelect {
        color: #209EE4;
        background: rgba(32, 158, 228, 0.1);
        border-radius: 3px 3px 3px 3px;
        border: 1px solid rgba(32, 158, 228, 0.3);
      }
    }

    .all_Btn {
      width: auto;
      height: 32px;
      background: #FFFFFF;
      border-radius: 3px 3px 3px 3px;
      border: 1px solid rgba(179, 192, 200, 0.3);
      text-align: center;
      cursor: pointer;
      padding: 8px;
      display: flex;
      align-items: center;
      margin-right: 20px;
    }

    .top_ul {
      display: flex;
      list-style: none;
      padding: 0;

      li {
        margin: 5px 0 0 -5px;
        cursor: pointer;
        color: #333333;

        &:first-of-type {
          border-block: .5em solid #0000;
          padding-inline: .5em calc(var(--r) + .25em);
          clip-path: polygon(100% 0, 0 0, 0 100%, 100% 100%, calc(100% - var(--r)) calc(100% - .25em), 100% 50%, calc(100% - var(--r)) .25em);
          background: border-box, #dddddd padding-box;
        }

        &:last-of-type {
          padding-left: calc(var(--r) + .25em);
          clip-path: polygon(100vw 0, 0 0, var(--r) 50%, 0 100%, 100vw 100%);
        }

        --r: .8em;
        border-block: .5em solid #0000;
        padding-left: calc(var(--r) + .25em);
        padding-inline: .5em calc(var(--r) + .25em);
        line-height: 1.8;
        clip-path: polygon(100vw 0, 0 0, var(--r) 50%, 0 100%, calc(100% - var(--r)) calc(100% - .25em), 100% 50%, calc(100% - var(--r)) .25em);
        background:border-box,
        #dddddd padding-box;

        &.before-green {
          background-color: rgba(22, 199, 22, 0.20);
          /* 在选中项之前的li（不包括第一个）变绿 */
          color: #16C716;
          /* 如果需要，可以添加文字颜色 */
        }

        &.selected {
          /* 当前选中的li的样式 */
          background-color: rgba(32, 158, 228, 1) !important;
          color: #FFFFFF;
        }
      }
    }
  }

  .bottom_table {
    position: relative;
    background: #ffffff;
    padding: 20px;

    .title {
      font-size: 20px;
      font-weight: bold;
    }

    .table_btnC {
      display: flex;
      align-items: baseline;
      position: absolute;
      bottom: 15px;
      left: 20px;
    }

    .result-wrap {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;
      align-items: center;
      min-height: 30px;
      line-height: 30px;
      //background: #fff;
      border-radius: 4px;

      .result-item {
        flex: 1;
        font-size: 12px;
        margin-right: 15px;
        border: 1px solid #ccc;
        padding: 3px 10px;
        border-radius: 4px;
        box-sizing: border-box;
      }

      .result-clear {
        color: #209ee4;
        cursor: pointer;
        font-size: 14px;
        border: 1px solid;
        padding: 1px 5px;
      }
    }

  }


  .tipes {
    font-size: 12px;
    color: #ccc;
    margin-bottom: 15px;
  }

  .filter-dropdown {
    padding: 8px;
    box-sizing: border-box;
    border: 1px solid #ccc;
  }

  .btn-hover,
  .btn-hover:hover {
    color: #209EE4;
  }

  :deep(.btn-hover>span:hover) {
    text-decoration: underline;
  }

  .custom-tag {
    padding: 4px 8px;
    border: none;
  }

  .tag-not-start {
    color: #FF4242;
    background-color: rgba(255, 66, 66, 0.1);
  }

  .tag-progress {
    color: #16C716;
    background: rgba(22, 199, 22, 0.1);
  }

  .tag-over {
    color: #999999;
  }

  .tag-normal {
    color: #F0A03D;
    background: rgba(240, 160, 61, 0.1);
  }

  .cannot-click {
    pointer-events: none;
    color: #ccc !important
  }
}
</style>